﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#region XNA Libraries

using Microsoft.Xna.Framework;

#endregion

#region SDK Libraries

using main.sdk.display.object2d;
using main.sdk.utils;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using main.sdk.input;
using Microsoft.Xna.Framework.Input;

#endregion

namespace main.src.game
{
    /**
     * Classe que controla a bola do jogo.
     */
    public sealed class Game_Ball
    {
        #region Public Variables

        public readonly  Game_Field ParentField = null;
        public const     float      Ray         = 13.0f;  

        #endregion

        #region Private Variables

        private Body    _Body         = null;
        private Vector2 _Position     = new Vector2(0, 0);
        private Sprite  _BallSprite   = new Sprite("RSC/Picture/Ball");

        #endregion

        #region Public Members

        /**
         * Construtor.
         */
        public Game_Ball(Game_Field parent)
        {
            ParentField = parent;

            _Body = BodyFactory.CreateCircle(parent.World, Ray / ParentField.Scale, 1.0f);
            _Body.BodyType        = BodyType.Dynamic;
            _Body.Restitution     = 0.6f;
            _Body.Friction        = 0.4f;
            _Body.LinearDamping   = 0.0f;
            _Body.IsBullet        = true;

            _BallSprite.OX = _BallSprite.Width / 2;
            _BallSprite.OY = _BallSprite.Height / 2;
        }

        /**
         * Posição da Bola.
         */
        public Vector2 Position
        {
            get { return _Position; }
            set { _Position = value; _Body.Position = Vector2.Multiply(_Position, 1.0f / ParentField.Scale); }
        }

        /**
         * Define os parametros da bola.
         */
        public void Setup(Vector2 Direction, float Speed)
        {
            Vector2 D = new Vector2(Direction.X, Direction.Y);
            D.Normalize();
            _Body.LinearVelocity = Vector2.Multiply(D, Speed / ParentField.Scale);
        }

        /**
         * Atualiza a bola
         */
        public void Update(double Time)
        {
            /* Atualiza o Sprite da bola */
            _BallSprite.Position = Vector2.Multiply(_Body.Position, ParentField.Scale);
            _BallSprite.Rotation = _Body.Rotation;
        }

        /**
         * Atualiza a parte de física da bola.
         */
        public void UpdatePhysics()
        {
            /* Aplica uma força horizonal em direção ao centro. */
            Vector2 Force = new Vector2((Program.Width / (2 * ParentField.Scale)) - _Body.Position.X, 0);
            _Body.ApplyForce(Vector2.Multiply(Force, 1));
        }

        #endregion
    }
}
